package org.afolsn.user

import org.springframework.security.core.authority.GrantedAuthorityImpl
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.orm.jpa.JpaCallback
import org.springframework.context.*
import org.springframework.beans.*
import org.springframework.orm.jpa.JpaTemplate
import javax.persistence.*

class UserDetailsServiceImpl implements UserDetailsService {

	def userService
	
	UserDetails loadUserByUsername(String username, boolean loadRoles) throws UsernameNotFoundException {
		return loadUserByUsername(username)
	}

	UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		def roles = ["ROLE_USER"]

		User user = userService.loadUser(username);
		
		if (!user)
		   throw new UsernameNotFoundException('User not found', username)

/*
   if(user.roles.superAdmin)
		   roles.add("ROLE_ADMIN");
   if(user.roles.groupAdmin)
		roles.add("ROLE_GROUP");
*/
		def authorities = roles.collect { new GrantedAuthorityImpl(it) }
	    return new SecurityUserDetails(user.login, user.password, true, true, true, true, authorities, 1, 'Test User')
	}
	
}
